面试官:StringBuilder和StringBuffer的区别在哪? 我:StringBuilder不是线程安全的,StringBuffer是线程安全的 面试官:那StringBuilder不安全的点在哪儿? 我:。。。(哑巴了)
在分析设个问题之前我们要知道StringBuilder和StringBuffer的内部实现跟String类一样,都是通过一个char数组存储字符串的,不同的是String类里面的char数组是final修饰的,是不可变的,而StringBuilder和StringBuffer的char数组是可变的。
public class StringBuilderDemo { public static void main(String[] args) throws InterruptedException { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 10; i++){ new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < 1000; j++){ stringBuilder.append("a"); } } }).start(); } Thread.sleep(100); System.out.println(stringBuilder.length()); }}
//存储字符串的具体内容char[] value;//已经使用的字符数组的数量int count;
@Overridepublic StringBuilder append(String str) { super.append(str); return this;}
public AbstractStringBuilder append(String str) { if (str == null) return appendNull(); int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0, len, value, count); count += len; return this;}
private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code if (minimumCapacity - value.length > 0) expandCapacity(minimumCapacity);}
void expandCapacity(int minimumCapacity) { //计算新的容量 int newCapacity = value.length * 2 + 2; //中间省略了一些检查逻辑 ... value = Arrays.copyOf(value, newCapacity);}
public static char[] copyOf(char[] original, int newLength) { char[] copy = new char[newLength]; //拷贝数组 System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy;}
str.getChars(0, len, value, count);
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { //中间省略了一些检查 ... System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); }
推荐阅读:Java面试题汇总(208道)
【END】
文章有问题?点此查看未经处理的缓存